#!/usr/bin/env python
# -*- coding:utf-8 -*-

import re
from models.sso_user import SsoUser
from controller.ssoUserController import SsoUserController
from controller.userClientController import UserClientController
from controller.userCounselorController import UserCounselorController
from utils.aes_encrypt_decrypt import AESEncryptDecrypt
from utils.rsa_encryption_decryption import RSAEncryptionDecryption
from utils.generate_id import GenerateID
from utils.jwt_util import JwtToken
from config import Config

class SsoUserService:
    @staticmethod
    def _determine_login_type(account):
        """
        根据账号格式判断登录类型
        :param account: 账号
        :return: login_type (str)
        """
        # 邮箱格式
        email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        # 手机号格式（中国大陆）
        mobile_pattern = r'^1[3-9]\d{9}$'
        
        if re.match(email_pattern, account):
            return '1'  # 邮箱
        elif re.match(mobile_pattern, account):
            return '3'  # 手机号
        else:
            return '2'  # 平台账号

    @staticmethod
    def register(account, password, name, gender=None, mobile=None, email=None, user_type=1, **kwargs):
        """
        用户注册服务
        :param account: 账号
        :param password: 加密后的密码
        :param name: 姓名
        :param gender: 性别
        :param mobile: 手机号
        :param email: 邮箱
        :param user_type: 用户类型 1-咨询者 2-咨询师
        :return: dict
        """
        try:
            # 1. 检查账号是否已存在
            exist_user = SsoUserController.get(account=account)
            if exist_user['code'] == "2000" and exist_user['data']:
                return {"code": "4003", "message": "账号已存在"}

            # 2. 解密密码
            decrypted_password = password
            if not decrypted_password:
                return {"code": "4002", "message": "密码解密失败"}

            # 3. 生成统一的user_id
            user_id = GenerateID.create_random_id()
            # 5. 创建SSO用户
            sso_user = SsoUserController.add(
                user_id=user_id,
                account=account,
                password=decrypted_password,
                login_type=1,
                user_type=user_type
            )

            # 6. 根据用户类型创建对应的用户信息
            if user_type == 1:
                # 创建咨询者信息
                client_result = UserClientController.add(
                    user_id=user_id,
                    name=name,
                    gender=gender,
                    mobile=mobile,
                    email=email
                )
                if client_result['code'] != "2000":
                    # 如果创建失败，需要回滚SSO用户
                    SsoUserController.delete(user_id=user_id)
                    return client_result

            elif user_type == 2:
                # 创建咨询师信息
                counselor_result = UserCounselorController.add(
                    user_id=user_id,
                    name=name,
                    gender=gender,
                    mobile=mobile,
                    email=email,
                    level=1,
                    certificate=kwargs.get('certificate'),
                    workplace=kwargs.get('workplace'),
                    status=0
                )
                if counselor_result['code'] != "2000":
                    # 如果创建失败，需要回滚SSO用户
                    SsoUserController.delete(user_id=user_id)
                    return counselor_result

            return {
                "code": "2000",
                "message": "注册成功",
                "data": {
                    "user_id": user_id,
                    "account": account,
                    "name": name,
                    "user_type": user_type,
                    "login_type":1
                }
            }

        except Exception as e:
            print(f"Register error: {str(e)}")  # 保留这一行日志记录
            return {
                "code": "5000",
                "message": "服务器内部错误",
                "error": str(e)
            }
    
    @staticmethod
    def login(account, password):
        """
        统一登录服务
        :param account: 账号
        :param password: 加密后的密码
        :return: dict
        """
        try:
            # 1. 在SSO用户表中查找用户
            sso_user = SsoUserController.get(account=account)
            if sso_user['code'] != "2000" or not sso_user['data']:
                return {"code": "4001", "message": "账号不存在"}

            sso_user_data = sso_user['data'][0] if isinstance(sso_user['data'], list) else sso_user['data']
            # 2. 解密前端传来的密码
            decrypted_password = RSAEncryptionDecryption.decrypt(password)
            if not decrypted_password:
                return {"code": "4002", "message": "密码解密失败"}
            # 3. 验证密码
            stored_password = sso_user_data['password']
            if decrypted_password != stored_password:
                return {"code": "4003", "message": "密码错误"}

            # 4. 生成token数据
            token_data = {
                "user_id": sso_user_data['user_id'],
                "user_type": sso_user_data['user_type'],
                "account": account
            }
            
            # 获取JWT配置
            jwt_config = Config.get_jwt_config()
            
            # 生成token
            token = JwtToken.generate_token(
                data=token_data,
                secret_key=jwt_config['secret_key'],
                expires_in=jwt_config['token_expires']
            )

            # 5. 只返回指定字段
            return {
                "code": "2000",
                "message": "登录成功",
                "data": {
                    "account": account,
                    "user_id": sso_user_data['user_id'],
                    "user_type": sso_user_data['user_type'],
                    "token": token
                }
            }

        except Exception as e:
            print(f"Login error: {str(e)}")  # 实际应该使用logger
            return {
                "code": "5000",
                "message": "服务器内部错误",
                "error": str(e)
            }
